package com.tledu.ssm.core.interceptor;

import com.tledu.ssm.core.constants.CommonConstants;
import com.tledu.ssm.model.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author cyrus
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        HandlerMethod handlerMethod = (HandlerMethod) handler;
//        // 获取请求需要执行的方法名，当前请求方法相关的一些操作
//        String methodName = handlerMethod.getMethod().getName();
        // 判断当前请求是否和登录操作相关
        HttpSession session = request.getSession(true);
        User loginUser = (User) session.getAttribute(CommonConstants.LOGIN_USER);
        if (loginUser == null) {
            response.sendRedirect(request.getContextPath() + "/");
            // 直接返回json，或者重定向到一个接口，总之告诉现在是没有登录状态的
            // 终止后续请求
            return false;
        }
        return super.preHandle(request, response, handler);
    }
}
